package com.example.app1;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.app1.Util.ViewUtil;

public class TextEditActivity extends AppCompatActivity implements View.OnFocusChangeListener {

    private EditText et_account;
    private EditText et_password;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_text_edit);
        et_account = findViewById(R.id.et_account);
        et_password = findViewById(R.id.et_password);
        et_account.setOnFocusChangeListener(this);
        et_password.addTextChangedListener(new HideKeyBoardTextWatcher(et_password,6));
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (v.getId() == R.id.et_password && hasFocus) {
            String account = et_account.getText().toString();
            if (TextUtils.isEmpty(account) || account.length() < 11) {
                //账号编辑框请求焦点，也就是将光标移回账号编辑框
                et_account.requestFocus();
                Toast.makeText(this, "请输入11位账号", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private class HideKeyBoardTextWatcher implements TextWatcher {
        private EditText et;//输入的编辑框
        private int closeNum;//关闭时的输入数量

        HideKeyBoardTextWatcher(EditText et, int numOnClose) {
            this.et = et;
            closeNum = numOnClose;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            String str=s.toString();
            if(str.length()==closeNum)
            {
                ViewUtil.hideOneInputMethod(TextEditActivity.this,et);
            }
        }
    }
}
